package serializableObjects;

import usersObjects.StorageOfUsers;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.File;
import java.io.FilenameFilter;

/**
 * Created with IntelliJ IDEA.
 * User: xpk
 * Date: 11/17/13
 * Time: 5:30 PM
 * To change this template use File | Settings | File Templates.
 */
public class SerializableMethods {
    public static void saveUsers(SerializableUser serializableUser) {
        try {
            FileOutputStream fos = new FileOutputStream(String.format("%s.%s", serializableUser.getUserLogin(), "user"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(serializableUser);
            oos.flush();
            oos.close();
            fos.close();
        } catch (Exception ex) {
            System.out.println("Backup error " + ex.toString());
        }
    }

    public static StorageOfUsers loadUsers() {
        File[] serializableFiles;
        StorageOfUsers storageOfUsers = new StorageOfUsers();

        serializableFiles = new File(".").listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".user");
            }
        });

        for (File s : serializableFiles) {
            try {
                FileInputStream is = new FileInputStream(s.getAbsoluteFile());
                ObjectInputStream ois = new ObjectInputStream(is);
                SerializableUser serializableUser = (SerializableUser) ois.readObject();
                storageOfUsers.downloadUserFromFiles(serializableUser);
                ois.close();
                is.close();
            } catch (Exception ex) {
                return new StorageOfUsers();
            }
        }
        return storageOfUsers;
    }
}
